package com.bloomberg.openmarket;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;
import java.util.logging.FileHandler;
import java.util.logging.Filter;
import java.util.logging.Formatter;
import java.util.logging.Level;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

import br.com.bb.provider.InformationProvider;
import br.com.bb.stock.Stock;

public class Bloomberg implements InformationProvider {
	private NumberFormat df = DecimalFormat.getInstance(Locale.US);
	private Map<String, Double> stockMap;
	private Logger logger;
	private FileHandler fh;
	private Formatter formatter;
	
	public Bloomberg() throws SecurityException, IOException {
		this.logger  = Logger.getLogger("LoggerService");
		this.logger.setUseParentHandlers(false);
		this.formatter = new Formatter() {
			@Override
			public String format(LogRecord record) {
				StringBuilder builder = new StringBuilder(1000);
				builder.append(formatMessage(record));
				builder.append("\n");
				return builder.toString();
			}
		};
		
		this.fh = new FileHandler("logProcessingTime.txt");
		this.fh.setFormatter(this.formatter);
		this.fh.setFilter(new Filter() {
			public boolean isLoggable(LogRecord record) {
				String msg = record.getMessage();
				if (msg.startsWith("ProcessingTime")) {
					return true;		
				}
				return false;
			}
		});
		this.logger.addHandler(fh);
		stockMap = new TreeMap<String, Double>();
		for (Stock stock : Stock.values()) {
			Random seed = new Random();
			double value = seed.nextDouble() * 10;
			stockMap.put(stock.getCode(), value);
		}
	}

	public String getName() {
		return "Bloomberg";
	}

	public double getCotation(Stock stock) {
		long start = System.currentTimeMillis();
		double currentPrice = stockMap.get(stock.getCode());
		double cotation = currentPrice;
		System.out.println(("=====>> " + this.getName()+ ": " + stock.getCode() + " - " + stock.getName() + ": " + currentPrice));
		Random random = new Random();
		boolean isPositive = random.nextBoolean();
		double variation = 0.05 * random.nextDouble();
		if (isPositive) {
			cotation = cotation + variation;
		} else {
			cotation = cotation - variation;
		}
		cotation = Double.valueOf(df.format(cotation));
		stockMap.put(stock.getCode(), cotation);
		
		StringBuilder builder = new StringBuilder(1000);
		builder.append("ProcessingTime").append(" - ");
		builder.append(System.currentTimeMillis()- start);
		logger.log(Level.INFO, builder.toString());
		return currentPrice;
	}

}
